import { tabListType } from "@/type/home"
import { useEffect, useState } from "react"
import { InfiniteScroll, Toast  } from 'antd-mobile'
import { getHomeGoods } from '@/api/home'
import { GetCategoryGoods } from '@/api/category'
import { UserCollect } from '@/api/mine'
import { useActivate } from "react-activation"
import { getCookie } from "@/utils"

const Lists = (props: tabListType) => {
    const [goodList, setGoodList] = useState<any>([])
    const [hasMore, setMore] = useState(true) // 是否还有更多内容
    const [error, setError] = useState(false) 
    const [pageNow, setPageNow] = useState(1)
    const [collectProductNum, setCollectProductNum] = useState(0) // 我的收藏产品的数量
     
    // 公共捕捉错误
    const getError = (err: {code: string}) => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') {
        setError(true)
        setMore(false)
      }
    }

    // 公共获取数据
    const getData = (data: []) => {
      setGoodList((oldList: []) => [...oldList, ...data])
      if (data.length < 10 || data.length === 0) {
        setMore(false) 
      }
    }

    // 数据初始化
    const init = async (pageCurrent: number) => {
      let res = null
      if(props.page === 'home') { // 首页List加载更多
        res = await getHomeGoods (props.type, pageCurrent).catch(err => {
          getError(err)
        })
      } else if(props.page === 'category') { // 分类页面List加载更多
        res = await GetCategoryGoods (props.type, props.menuID, pageCurrent).catch(err => {
          getError(err)
        })
      } else {
        console.log()
        res = await UserCollect (pageCurrent).catch(err => {
          getError(err)
        })
      }

      if(res?.status === 200) {
        setError(false)
        setMore(true)
        setPageNow(pageNow+1)
        if(props.page === 'collect') { // 收藏页面
          getData(res.data.data)
          setCollectProductNum(res.data.data.length)
        } else { // 首页 和 分类页面
          getData(res.data.goods.data)
        }
      }
    }

    const loadMore = async () => { await init(pageNow) }

    useEffect(() => {
      if(props.page === 'category') {
        setGoodList([])
        setMore(true)
        setPageNow(1)
      }
    }, [props.menuID, props.page])

    useActivate(() => {
      if(props.page === 'collect' && (collectProductNum !== getCookie('collectNum'))) {
        setPageNow(1)
        setGoodList([])
        init(1)
      }
    })
    
    return (
    <>
     {props.getlist(goodList)}
     <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
       {(hasMore, failed, retry) => {
         if(error) {
           return <span onClick={() => Toast.show({icon: 'loading', content: '加载中...', afterClose: () => retry()})}>加载失败, 重新加载</span>
         } else if(!hasMore) {
           return <span>没有更多了</span>
         } else {
           return <span>加载中...</span>
         }
       }}
     </InfiniteScroll>
    </>
  )
}
export default Lists